<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/13 0013
 * Time: 17:26
 */

namespace backend\controllers;


use backend\components\BaseComponentController;
use common\components\DataHelper;
use common\models\Admin\Admin;
use common\models\PercentageItem\PercentageItem;
use common\models\PlugsRunDesc\PlugsRunDesc;
use common\models\PlugsRunTotal\PlugsRunTotal;
use yii\helpers\Url;

class ReportController extends BaseComponentController
{
    public function actionQuery(){
        $id = $this->get('id');
        $date = $this->get('date', date("Y-m-d"));
        $ret = PlugsRunTotal::findOne(['agent_uid'=>$id, 'created_date'=>$date]);
        if(!$ret) DataHelper::outMsg('0:没有此数据', 'nil');

        echo sprintf('代理ID：%s[%s-%s]， 日期：%, 成功数：%s，失败数：%s', $id, $ret->province, $ret->city, $date, $ret->terminal_num, $ret->fail_terminal_num);
    }
    public function actionIndex()
    {
        $parentAgent = $this->get("parent_agent", 0);
        $percentageItem = PercentageItem::find()->where([
            "parent_agent" => intval($parentAgent)
        ]);
        PercentageItem::createSearchCondition($percentageItem, $this->get());

        //克隆一份汇总数据 不带分组的数据
        $percentageItemClone = clone $percentageItem;
        $percentageItemClone->select([
            "sum(upper_num) as terminal_num",
            "count(distinct created_date) as days",
        ]);

        $percentageItem->with(["agentInfo"=> function($query){
            $query->select(["uid", "name"]);
        }, "managerInfo"=> function($query){
            $query->select(["uid", "name"]);
        }]);

        //区域经理
        if ( $this->isManager() ) {
            $percentageItem->andWhere([
                "manager_id" => $this->uid
            ])->groupBy("created_date, agent_id");

            $percentageItemClone->andWhere([
                "manager_id" => $this->uid
            ]);
        } elseif ( $this->isAgent() ) {
            //这里表示检索下级代理
            if ( $parentAgent ) {
                if ( $parentAgent != $this->uid ) {
                    return "error";
                }
            } else {
                $percentageItemClone->andWhere([
                    "agent_id" => $this->uid
                ]);
                $percentageItem->andWhere([
                    "agent_id" => $this->uid
                ])->groupBy("created_date, manager_id");
            }
        }

        if ( $this->isAdmin() ) {
            $percentageItem->groupBy("created_date, agent_id, manager_id");
        }
        $page = DataHelper::getPage($percentageItem->count());
        $plugsRunTotal = $percentageItem->orderBy("created_date desc")->offset($page->offset)->limit($page->limit)->asArray()->all();
        if ( $parentAgent ) {
            $this->layout = self::LAYER_CONTENT;
        }
        return $this->render("index", [
            "page" => $page,
            "ret" => $plugsRunTotal,
            "totalRet" => $percentageItemClone->asArray()->one()

        ]);

    }



    /**
     * 地区图表
     */
    public function actionDetailArea()
    {
        // 一级行政区
        $plugsRunTotalProvince = PercentageItem::find();
        $plugsRunTotalProvince->select([
            'province',
            'SUM(upper_num) AS terminal_num_sum',
        ]);
        PercentageItem::createSearchCondition($plugsRunTotalProvince, $this->get());
        if ($this->isManager()) { // 区域经理
            $plugsRunTotalProvince->andWhere([
                'manager_id' => $this->uid
            ])->groupBy('created_date, agent_id, province');
        } elseif ($this->isAgent()) {
            $plugsRunTotalProvince->andWhere([
                'agent_id' => $this->uid
            ])->groupBy('created_date, manager_id, province');
        }
        if ($this->isAdmin()) {
            $plugsRunTotalProvince->groupBy('created_date, agent_id, manager_id, province');
        }
        $plugsRunTotalProvinceList = $plugsRunTotalProvince->asArray()->all();

        // 二级行政区
        $plugsRunTotalCity = PercentageItem::find();
        $plugsRunTotalCity->select([
            'city',
            'SUM(upper_num) AS terminal_num_sum',
        ]);
        PercentageItem::createSearchCondition($plugsRunTotalCity, $this->get());
        if ($this->isManager()) { // 区域经理
            $plugsRunTotalCity->andWhere([
                'manager_id' => $this->uid
            ])->groupBy('created_date, agent_id, city');
        } elseif ($this->isAgent()) {
            $plugsRunTotalCity->andWhere([
                'agent_id' => $this->uid
            ])->groupBy('created_date, manager_id, city');
        }
        if ($this->isAdmin()) {
            $plugsRunTotalCity->groupBy('created_date, agent_id, manager_id, city');
        }
        $plugsRunTotalCityList = $plugsRunTotalCity->asArray()->all();
        $this->layout = self::LAYER_CONTENT;
        return $this->render('detail-area', [
            'plugsRunTotalProvinceList' => $plugsRunTotalProvinceList,
            'plugsRunTotalCityList' => $plugsRunTotalCityList,
        ]);
    }

    /**
     * 代理商月结数据
     * @return string
     */
    public function actionAgent()
    {
        /*if ( $this->isAgent() ) {
            return "error";
        }*/
        $ym = $this->get("ym", date("Y-m"));
        $percentageItem = PercentageItem::find()->where([
            "created_ym" => $ym,
        ])->select([
            "agent_id",
            "sum(upper_num) as terminal_num",
            "count(distinct created_date) as days",
            "created_ym",
            "agent_status",
            "manager_id",
            "plug_id"
        ])->with("yesterdayAgentNum");
        if ( $this->isManager() ) {
            $percentageItem->andWhere([
                "manager_id" => $this->uid
            ]);
        } elseif ( $this->isAgent() ) {
            $percentageItem->andWhere([
                "parent_agent" => $this->uid
            ]);
        } else {
            $percentageItem->andWhere([
                "parent_agent" => 0
            ]);
        }
        PercentageItem::createSearchCondition($percentageItem, $this->get());
        $percentageItemClone = clone $percentageItem;

        $percentageItem->with(["agentInfo"=> function($query){
            $query->select(["uid", "name", "rev_price_image", "ali_account"]);
        }])->groupBy("agent_id");

        $page = DataHelper::getPage($percentageItem->count());
        $plugsRunTotal = $percentageItem->offset($page->offset)->limit($page->limit)->asArray()->all();
        return $this->render("agent", [
            "page" => $page,
            "ret" => $plugsRunTotal,
            "totalRet" => $percentageItemClone->asArray()->one()
        ]);
    }

    public function actionSettlement()
    {
        $condition = [
            "created_ym" => $this->get("ym")
        ];
        if ( $this->requestAll("type") == "agent" ) {
            $condition["agent_id"] = $this->requestAll("uid");
            $updateField = "agent_status";
        } else {
            $condition["manager_id"] = $this->requestAll("uid");
            $condition["parent_agent"] = 0;//顶级代理的数量包含了 下级代理
            $updateField = "manager_status";
        }
        $ret = PercentageItem::updateAll([
            $updateField => PercentageItem::STATUS_YES
        ], $condition);
        if ( !$ret ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, "标记失败");
        }
        return $this->jsonResponse(self::RESPONSE_SUCCESS);
    }

    /**
     * 区域总经理月结数据
     * @return string
     */
    public function actionManager()
    {
        $ym = $this->get("ym", date("Y-m"));
        $percentageItem = PercentageItem::find()->where([
            "created_ym" => $ym,
            "parent_agent" => 0
        ])->select([
            "manager_id",
            "sum(upper_num) as terminal_num",
            "count(distinct created_date) as days",
            "created_ym",
            "manager_status",
            "agent_status",
        ])->with("yesterdayManagerNum");;
        PercentageItem::createSearchCondition($percentageItem, $this->get());
        $percentageItemClone = clone $percentageItem;
        $percentageItem->with(["managerInfo"=> function($query){
            $query->select(["uid", "name", "rev_price_image"]);
        }])->groupBy("manager_id");

        $page = DataHelper::getPage($percentageItem->count());
        $plugsRunTotal = $percentageItem->offset($page->offset)->limit($page->limit)->asArray()->all();
        return $this->render("manager", [
            "page" => $page,
            "ret" => $plugsRunTotal,
            "totalRet" => $percentageItemClone->asArray()->one()
        ]);
    }

    public function actionP2p(){

        $agent_id = (int)$this->get('key');
        $date = DataHelper::qVal('date','%ymd', date("Y-m-d"), $this->get());
        $p2p = PlugsRunDesc::find()->select('agent_id, ip, count(id) num')->where(['created_date'=>$date,'p2p'=>0])->groupBy('ip,agent_id');
        if($agent_id) $p2p->andWhere(['agent_id'=>$agent_id]);

        $p2p->with(["agentInfo"=> function($query){$query->select(["uid", "name"]);}]);

        $page = DataHelper::getPage($p2p->count());
        $plugsRunTotal = $p2p->orderBy("num desc,agent_id asc")->offset($page->offset)->limit($page->limit)->asArray()->all();

        return $this->render("p2p", [
            "page" => $page,
            "ret" => $plugsRunTotal,
            "total" => PlugsRunDesc::find()->where(['created_date'=>$date,'p2p'=>0])->count('id')
        ]);
    }
}